package com.sctvcloud.beichuan.ui.activities;

import android.app.ActivityManager;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Pair;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.githang.statusbar.StatusBarCompat;
import com.gridsum.tracker.GridsumWebDissector;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.beichuan.R;
import com.sctvcloud.beichuan.application.Cache;
import com.sctvcloud.beichuan.base.BaseActivity;
import com.sctvcloud.beichuan.base.BaseFragment;
import com.sctvcloud.beichuan.beans.ServiceCityListVo;
import com.sctvcloud.beichuan.beans.UserInfoBean;
import com.sctvcloud.beichuan.http.AbsNetCallBack;
import com.sctvcloud.beichuan.http.NetUtils;
import com.sctvcloud.beichuan.ui.fragment.ColumnBaseFragment;
import com.sctvcloud.beichuan.ui.fragment.HomeFragment;
import com.sctvcloud.beichuan.ui.fragment.MineFragment;
import com.sctvcloud.beichuan.ui.fragment.PlatFormFragment;
import com.sctvcloud.beichuan.ui.fragment.ServiceFragment;
import com.sctvcloud.beichuan.ui.fragment.ShortVideoFragment;
import com.sctvcloud.beichuan.ui.manager.AdPictureManager;
import com.sctvcloud.beichuan.utils.UserManager;
import com.sctvcloud.beichuan.utils.VersionUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class MyMainActivity extends BaseActivity {
    @BindView(R.id.container)
    protected FrameLayout container;
    @BindView(R.id.tab_1)
    protected TextView tab1;
    @BindView(R.id.tab_2)
    protected TextView tab2;
    @BindView(R.id.tab_3)
    protected TextView tab3;
    @BindView(R.id.tab_4)
    protected TextView tab4;
    @BindView(R.id.short_btn)
    protected RelativeLayout shortVideoBtn;
    @BindView(R.id.short_icon)
    protected ImageView shortVideoBtnIcon;
    @BindView(R.id.short_name)
    protected ImageView shortVideoBtnName;
    private BaseFragment currentFragment;
    private Handler handler;
    private static final int GET_AD_IMG = 0;
    private static final int TO_PLAY_VIDEO = 1001;
    private AdPictureManager adPicManager;
    private int currentTabIndex = -1;
    ArrayList<Pair<String, String>> pairs = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.red_E42417));
        pairs.add(new Pair<>("页面", "导航"));
        pairs.add(new Pair<>("行为类型", "点击"));
        SharedPreferencesUtil.setParam(this, "FLOAT_AD", true);
        HomeFragment hFragment = new HomeFragment();
        PlatFormFragment pFragment = new PlatFormFragment();
        ShortVideoFragment shFragment = new ShortVideoFragment();
        ServiceFragment seFragment = new ServiceFragment();
        MineFragment mFragment = new MineFragment();

//        addTab("首页", R.mipmap.icon_home_unsel,
//                R.mipmap.icon_home_sel, HomeFragment.class, true);
//        addTab("微平台", R.mipmap.icon_home_weipingtai_unsel,
//                R.mipmap.icon_home_weipingtai_sel, PlatFormFragment.class, true);
//        addTab("短视频", R.mipmap.all_icon_tabplay,
//                R.mipmap.all_icon_tabplay_pressed, ShortVideoFragment.class, true);
//        addTab("服务", R.mipmap.icon_home_service_unsel,
//                R.mipmap.icon_home_service_sel, ServiceFragment.class, true);
//        addTab("我的", R.mipmap.icon_home_mine_unsel,
//                R.mipmap.icon_home_mine_sel, MineFragment.class, true);
//        commit(R.color.colorFontSelect);
//        initData();
        onTabChanged(0);
        initPush();
        /*********************启动定时获取启动页广告图片的进程***************************/
        adPicManager = new AdPictureManager(this);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg != null && msg.what == GET_AD_IMG) {
                    requestAd();
                }
            }
        };
        adPicManager.startAdService(handler, GET_AD_IMG);
        /******************************************************************8****/
//        getServiceConfig();
        initUserData();
        SharedPreferencesUtil.setParam( this, SplashActivity.START_KEY, false);
        int versionCode = VersionUtil.getVersionCode(this);
        SharedPreferencesUtil.setParam(this, SplashActivity.APP_VERSION_KEY, versionCode);

//        setCenterClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(MainActivity.this, ShortVideoFragment.class);
//                startActivityForResult(intent, TO_PLAY_VIDEO);
//                GridsumWebDissector.getInstance().trackEvent(MainActivity.this, "", "播放", "", 200, pairs);
//            }
//        });
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    private void requestAd() {
        adPicManager.requestAdPic(this + "");
    }

    /**
     * 初始化推送状态
     */
    private void initPush() {
        boolean isPush = (boolean) SharedPreferencesUtil.getParam(this, "PUSH_KEY", true);
        if (isPush) {
            //设置开启推送
            SharedPreferencesUtil.setParam(this, "PUSH_KEY", true);
            JPushInterface.resumePush(this);
            JPushInterface.setAlias(this, 0, "scgc2_0");
        } else {
            //停止推送服务
            JPushInterface.stopPush(this);
        }


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }


    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            bottom_lay.setVisibility(View.GONE);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//            bottom_lay.setVisibility(View.VISIBLE);
        }
    }

    @OnClick(value = {R.id.tab_1, R.id.tab_2, R.id.tab_3, R.id.tab_4, R.id.short_btn})
    public void tabClick(View view) {
        switch (view.getId()) {
            case R.id.tab_1:
                onTabChanged(0);
                break;
            case R.id.tab_2:
                onTabChanged(1);
                break;
            case R.id.short_btn:
                onTabChanged(2);
                break;
            case R.id.tab_3:
                onTabChanged(3);
                break;
            case R.id.tab_4:
                onTabChanged(4);
                break;

        }
    }

    public void onTabChanged(int index) {
        if (currentTabIndex != index) {
            BaseFragment fragment = null;
            Drawable top1 = getResources().getDrawable(R.mipmap.icon_home_unsel);
            tab1.setCompoundDrawablesWithIntrinsicBounds(null, top1, null, null);
            tab1.setTextColor(getResources().getColor(R.color.multiStateButtonDisabled));
            Drawable top2 = getResources().getDrawable(R.mipmap.icon_home_weipingtai_unsel);
            tab2.setCompoundDrawablesWithIntrinsicBounds(null, top2, null, null);
            tab2.setTextColor(getResources().getColor(R.color.multiStateButtonDisabled));
            Drawable top3 = getResources().getDrawable(R.mipmap.icon_home_service_unsel);
            tab3.setCompoundDrawablesWithIntrinsicBounds(null, top3, null, null);
            tab3.setTextColor(getResources().getColor(R.color.multiStateButtonDisabled));
            Drawable top4 = getResources().getDrawable(R.mipmap.icon_home_mine_unsel);
            tab4.setCompoundDrawablesWithIntrinsicBounds(null, top4, null, null);
            tab4.setTextColor(getResources().getColor(R.color.multiStateButtonDisabled));
            shortVideoBtnIcon.setImageResource(R.mipmap.all_icon_tabplay);
            shortVideoBtnName.setImageResource(R.mipmap.all_icon_duanshipin);
            switch (index) {
                case 0: //首页
                    addFragment("HomeFragment");
                    currentTabIndex = index;
                    GridsumWebDissector.getInstance().trackEvent(this, "", "首页", "", 200, pairs);
                    top1 = getResources().getDrawable(R.mipmap.icon_home_sel);
                    tab1.setCompoundDrawablesWithIntrinsicBounds(null, top1, null, null);
                    tab1.setTextColor(getResources().getColor(R.color.colorFontSelect));
                    if (UserManager.isLoginS()) {
                        StatisticsMainInit.newsInfoVisit(UserManager.getInstance().getUser().getPhoneNumber(), "",
                                "首页", "","0");
                    } else {
                        StatisticsMainInit.newsInfoVisit("", "",
                                "首页", "","0");
                    }
                    break;
                case 1:  //报料
                    addFragment("PlatFormFragment");
                    currentTabIndex = index;
                    GridsumWebDissector.getInstance().trackEvent(this, "", "微平台", "", 200, pairs);
                    top2 = getResources().getDrawable(R.mipmap.icon_home_weipingtai_sel);
                    tab2.setCompoundDrawablesWithIntrinsicBounds(null, top2, null, null);
                    tab2.setTextColor(getResources().getColor(R.color.colorFontSelect));
                    if (UserManager.isLoginS()) {
                        StatisticsMainInit.newsInfoVisit(UserManager.getInstance().getUser().getPhoneNumber(), "",
                                "微平台", "","0");
                    } else {
                        StatisticsMainInit.newsInfoVisit("", "",
                                "微平台", "","0");
                    }
                    break;
                case 2:   //播放
                    addFragment("ShortVideoFragment");
                    currentTabIndex = index;
                    GridsumWebDissector.getInstance().trackEvent(this, "", "短视频", "", 200, pairs);
                    shortVideoBtnIcon.setImageResource(R.mipmap.all_icon_tabplay_pressed);
                    shortVideoBtnName.setImageResource(R.mipmap.all_icon_duanshipin_pressed);
                    if (UserManager.isLoginS()) {
                        StatisticsMainInit.newsInfoVisit(UserManager.getInstance().getUser().getPhoneNumber(), "",
                                "短视频", "","0");
                    } else {
                        StatisticsMainInit.newsInfoVisit("", "",
                                "短视频", "","0");
                    }
                    break;
                case 3:   //服务
                    addFragment("ServiceFragment");
                    currentTabIndex = index;
                    GridsumWebDissector.getInstance().trackEvent(this, "", "服务", "", 200, pairs);
                    top3 = getResources().getDrawable(R.mipmap.icon_home_service_sel);
                    tab3.setCompoundDrawablesWithIntrinsicBounds(null, top3, null, null);
                    tab3.setTextColor(getResources().getColor(R.color.colorFontSelect));
                    if (UserManager.isLoginS()) {
                        StatisticsMainInit.newsInfoVisit(UserManager.getInstance().getUser().getPhoneNumber(), "",
                                "服务", "","0");
                    } else {
                        StatisticsMainInit.newsInfoVisit("", "",
                                "服务", "","0");
                    }
                    break;
                case 4:   //我的
                    addFragment("MineFragment");
                    currentTabIndex = index;
                    GridsumWebDissector.getInstance().trackEvent(this, "", "我的", "", 200, pairs);
                    top4 = getResources().getDrawable(R.mipmap.icon_home_mine_sel);
                    tab4.setCompoundDrawablesWithIntrinsicBounds(null, top4, null, null);
                    tab4.setTextColor(getResources().getColor(R.color.colorFontSelect));
                    if (UserManager.isLoginS()) {
                        StatisticsMainInit.newsInfoVisit(UserManager.getInstance().getUser().getPhoneNumber(), "",
                                "我的", "","0");
                    } else {
                        StatisticsMainInit.newsInfoVisit("", "",
                                "我的", "","0");
                    }
                    break;
            }
//            if (fragment != null) {
//                getSupportFragmentManager().beginTransaction().add(R.id.container, fragment).commitAllowingStateLoss();
//            }
        }
    }

    private void addFragment(String fTag) {
        //判断这个标签是否存在Fragment对象,如果存在则返回，不存在返回null
        BaseFragment fragment = (BaseFragment) getSupportFragmentManager().findFragmentByTag(fTag);
        //初始化Fragment事物
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // 如果这个fragment不存于栈中
        if (fragment == null) {
            //根据RaioButton点击的Button传入的tag，实例化，添加显示不同的Fragment
            if (fTag.equals("HomeFragment")) {
                fragment = new HomeFragment();
            } else if (fTag.equals("PlatFormFragment")) {
                fragment = new PlatFormFragment();
            } else if (fTag.equals("ShortVideoFragment")) {
                fragment = new ShortVideoFragment();
            } else if (fTag.equals("ServiceFragment")) {
                fragment = new ServiceFragment();
            } else if (fTag.equals("MineFragment")) {
                fragment = new MineFragment();
            }
            //在添加之前先将上一个Fragment隐藏掉
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
            transaction.add(R.id.container, fragment, fTag);
            transaction.commitAllowingStateLoss();
            //更新可见
            currentFragment = fragment;
        } else {
            //如果添加的Fragment已经存在，则将隐藏掉的Fragment再次显示,其余当前
            transaction.show(fragment);
            transaction.hide(currentFragment);
            //更新可见
            currentFragment = fragment;
            transaction.commitAllowingStateLoss();
        }


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

        exit();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    //退出时的时间
    private long mExitTime;

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MyMainActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            manager.restartPackage(getPackageName());
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    android.os.Process.killProcess(android.os.Process.myPid());
                    System.exit(0);
                }
            },2000);
        }
    }

//    /**
//     * 初始化请求服务城市配置数据
//     */
//    private void getServiceConfig() {
//        NetUtils.getNetAdapter().getServiceConfigData(getOwnerName(), ServiceFragment.configUrl, new AbsNetCallBack<ServiceConfigBean>(ServiceConfigBean.class) {
//            @Override
//            public void onSuc(ServiceConfigBean config) {
//                if (null != config) {
//                    getCityList(config.getUrl());
//                }
//            }
//
//            @Override
//            public void onEnd() {
//                super.onEnd();
//            }
//
//            @Override
//            public void onError(Throwable ex, String errorMsg) {
//                super.onError(ex, errorMsg);
//            }
//        });
//    }

    /**
     * 请求服务城市列表
     *
     * @param url
     */
    private void getCityList(String url) {
        if (TextUtils.isEmpty(url)) {

            return;
        }
        NetUtils.getNetAdapter().getServiceCityList(getOwnerName(), url, new AbsNetCallBack<ServiceCityListVo>(ServiceCityListVo.class) {
            @Override
            public void onSuc(ServiceCityListVo vo) {
                if (null != vo.getListInfo()) {
                    Cache.getInstance().setServiceCityList(vo.getListInfo());
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        SharedPreferencesUtil.setParam(this, "FLOAT_AD", true);
    }

    /**
     * 请求用户相关数据，积分、邀请码等
     */
    private void initUserData() {
        if (UserManager.getInstance().isLogin()) {
            //TODO 查询用户积分数据
            ArrayMap<String, Object> p = new ArrayMap<>();
            p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
            p.put("token", UserManager.getInstance().getUser().getToken());
            NetUtils.getNetAdapter().postGetUserData(getOwnerName(), p, new AbsNetCallBack<UserInfoBean>(UserInfoBean.class) {
                @Override
                public void onSuc(UserInfoBean userInfoBean) {
                    Cache.getInstance().setUserInfo(userInfoBean);
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                }
            });
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TO_PLAY_VIDEO) {
//            setCurrentTab(currentTabIndex);
        }
    }
}

